package httputil

import (
	log "auth/collector/logger"
	"bytes"
	"io/ioutil"
	"net/http"
	"time"
)

var (
	httpClient *http.Client
)

const (
	MaxIdleConns           = 100
	MaxIdleConnections int = 80
	RequestTimeout     int = 30
)

// init HTTPClient
func init() {
	httpClient = createHTTPClient()
}

// createHTTPClient for connection re-use
func createHTTPClient() *http.Client {
	client := &http.Client{
		Transport: &http.Transport{
			MaxIdleConns:        MaxIdleConns,
			MaxIdleConnsPerHost: MaxIdleConnections,
		},
		Timeout: time.Duration(RequestTimeout) * time.Second,
	}
	return client
}

func DoRequest(method string, url string, data string, headers map[string]string) (res string, err error) {

	req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(data)))
	if err != nil {
		log.Error(err.Error())
		return "", err
	}

	req.Header.Set("Content-Type", "application/json")
	for k, v := range headers {
		req.Header.Set(k, v)
	}

	resp, err := httpClient.Do(req)
	if err != nil {
		log.Error(err.Error())
		return "", err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Error(err.Error())
		return "", err
	}

	return string(body), nil
}

func DoRequestRaw(method string, url string, data string, headers map[string]string) (res string, err error) {
	client := &http.Client{}

	/*	req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(data)))
		if err != nil {
			utiltools.LogError(err.Error())
			return "", err
		}
		req.Header.Set("Content-Type", "application/json")
		for k, v := range headers {
			req.Header.Set(k, v)
		}*/

	resp, err := client.Post(url, "application/json", bytes.NewBuffer([]byte(data)))

	if err != nil {
		log.Error(err.Error())
		return "", err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Error(err.Error())
		return "", err
	}
	return string(body), nil
}
